using System.ComponentModel.Composition.Hosting;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows;
using Caliburn.Micro;
using Paladyne.FileSearch.Core;

namespace Paladyne.FileSearch.UI
{
    public partial class App : Application
    {
        public static readonly string ExtensionsPath = @".\Extensions";

        public App()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Loads all new assemblies in \Extensions folder if any
        /// </summary>
        public static void RefreshExtensions()
        {
            if (Directory.Exists(ExtensionsPath))
            {
                var directoryCatalog = IoC.Get<DirectoryCatalog>();
                directoryCatalog.Refresh();

                foreach (
                    FileInfo fileInfo in
                        new DirectoryInfo(ExtensionsPath).GetFiles().Where(f => f.Extension.ToLower() == ".dll"))
                {
                    AssemblySource.Instance.Add(Assembly.LoadFrom(fileInfo.FullName));
                }
            }
            else
            {
                IoC.Get<IDisplayMessage>().ShowError(
                    UI.Properties.Resources.App_RefreshExtensions_Extensions_folder_not_found);
            }
        }

        /// <summary>
        /// Scan the extensions folder to load new assemblies if any
        /// </summary>
        /// <param name="directoryCatalog"></param>
        public static void RefreshExtensions(DirectoryCatalog directoryCatalog)
        {
            directoryCatalog.Refresh();

            foreach (
                FileInfo fileInfo in
                    new DirectoryInfo(ExtensionsPath).GetFiles().Where(f => f.Extension.ToLower() == ".dll"))
            {
                AssemblySource.Instance.Add(Assembly.LoadFrom(fileInfo.FullName));
            }
        }
    }
}